/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vale.test.myHandlers;

import java.io.File;
import java.util.Stack;
import javax.swing.JTextArea;
import vale.sax.SaxException;
import vale.sax.ContentHandler;
import vale.miniDOM.XMLTree;
import vale.miniDOM.XmlElement;

/**
 *
 * @author juan
 */
public final class MyContentHandler implements ContentHandler {

    private static String TAB_CHAR = ">";
    private static int TAB = 8;
    private XMLTree dom;
    private String fullXML;
    private String fileName;
    private Stack<XmlElement> stk;
    private int tab = 0;
    private JTextArea outPut;

    public MyContentHandler(File xmlFile) {
        this.fileName = xmlFile.getAbsolutePath();
        this.dom = new XMLTree(fileName);
        this.stk = new Stack<XmlElement>();
        this.fullXML = "";
    }

    public XMLTree getDom() {
        return dom;
    }

    public String getFullXML() {
        return fullXML;
    }

    public void setOutput(JTextArea jTextArea) {
        this.outPut = jTextArea;
    }

    public void startDocument() throws SaxException {
        print("--- " + this.fileName + " ---");
    }

    public void endDocument() throws SaxException {
        print("--- EOF ---");
        this.stk.clear();
        System.gc();
    }

    public void startElement(String tag) throws SaxException {
        XmlElement element = new XmlElement(tag);
        if (stk.isEmpty()) {
            this.dom.setRoot(element);
        } else {
            this.stk.peek().addElement(element);
        }
        this.stk.add(element);
        print(tag);
        this.setTab(true);
    }

    public void endElement(String tag) throws SaxException {
        if (!stk.empty()) {
            this.stk.pop();
        }
        if (!tag.endsWith("/>")) {
            print(tag);
            this.setTab(false);
        }
    }

    public void insertContent(String content) throws SaxException {
        print(content);
        this.stk.peek().addContent(content);
    }

    public void DtdData(String tag) throws SaxException {
        print(tag);
        this.dom.setDocType(tag);
    }

    public void DocInfo(String tag) throws SaxException {
        print(tag);
        this.dom.setDocInfo(tag);
    }

    private void setTab(boolean increment) {
        if (increment) {
            this.tab += MyContentHandler.TAB;
        } else {
            this.tab -= MyContentHandler.TAB;
            if (this.tab < 0) {
                this.tab = 0;
            }
        }
    }

    private void print(String msg) {
        String preChars = "";
        for (int i = 0; i < this.tab; i++) {
            preChars += MyContentHandler.TAB_CHAR;
        }
        String finalMsg = preChars + " " + msg;
        this.fullXML += "\n" + finalMsg;
        System.out.println(finalMsg);
        if (this.outPut != null) {
            this.outPut.append("\n" + msg);
        }
    }
}
